package com.gexiaobao.pigeon.ui.pigeoncatcher

import android.os.Bundle
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.amap.api.maps.MapsInitializer
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.initFooter
import com.gexiaobao.pigeon.app.ext.loadListData
import com.gexiaobao.pigeon.app.ext.loadServiceInit
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.model.bean.CarListBean
import com.gexiaobao.pigeon.app.util.KvUtils
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.ActivityOrderSquareBinding
import com.gexiaobao.pigeon.permissions.PermissionInterceptor
import com.gexiaobao.pigeon.ui.adapter.AdapterOrderSquare
import com.gexiaobao.pigeon.ui.dialog.RxDialogCarList
import com.gexiaobao.pigeon.ui.dialog.RxDialogDefault
import com.gexiaobao.pigeon.ui.dialog.RxDialogSingle
import com.gexiaobao.pigeon.ui.fragment.mine.organization.activity.ActivityAddCarInfo
import com.gexiaobao.pigeon.viewmodel.PigeonCatcherViewModel
import com.google.gson.Gson
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.kingja.loadsir.core.LoadService
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.LogUtils
import me.hgj.jetpackmvvm.util.startActivity
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody

/**
 * @Author      : hxw
 * @Date        : 2024/6/24 13:59
 * @Describe    : 订单广场
 */
class ActivityOrderSquare : BaseActivity<PigeonCatcherViewModel, ActivityOrderSquareBinding>() {

    private var orderId: Int = 0
    private val mAdapter: AdapterOrderSquare by lazy { AdapterOrderSquare(arrayListOf()) }
    private lateinit var loadsir: LoadService<Any>

    private lateinit var locationClient: AMapLocationClient
    private var driverLng = 0.0
    private var driverLat = 0.0
    private var mOrgId = 0
    private var mTransporterId = 0
    private var address = ""
    private var mCarId = 0

    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        //隐私合规接口
        MapsInitializer.updatePrivacyShow(this, true, true)
        MapsInitializer.updatePrivacyAgree(this, true)

        //状态页配置
        loadsir = loadServiceInit(mDatabind.includeList.swipeRefreshLayout) {
            //点击重试时触发的操作
            onRefresh(true, driverLng, driverLat)
        }
        initLocation()

        mDatabind.includeBar.tvTitle.text = "订单广场"
        mDatabind.includeBar.tvRightMenu.isVisible = true
        mDatabind.includeBar.tvRightMenu.text = "个人中心"

        mDatabind.includeList.swipeRecyclerView.init(LinearLayoutManager(this), mAdapter).let {
            it.addItemDecoration(SpaceItemDecoration(0, Util.dp2px(this, 10f)))
            it.initFooter {
                onRefresh(false, driverLng, driverLat)
            }
        }

        mDatabind.includeList.swipeRefreshLayout.init {
            onRefresh(true, driverLng, driverLat)
        }

        mAdapter.setOnItemClickListener { _, _, position ->
            startToDetail(mAdapter.data[position].id, mAdapter.data[position].orgName)
        }

        mAdapter.addChildClickViewIds(R.id.tvReceiptOrder)
        mAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.tvReceiptOrder -> {//1创建2发布3已接单4已接鸽5已完成
                    address = mAdapter.data[position].address
                    mOrgId = mAdapter.data[position].orgId
                    when (mAdapter.data[position].status) {
                        2 -> {
                            orderId = mAdapter.data[position].id
                            showLoading(getString(R.string.loading))
                            mViewModel.getTransporterApplyCarList()
                        }

                        4 -> startToDetail(mAdapter.data[position].id, mAdapter.data[position].orgName)

                        3 -> {
                            startActivity<ActivityOrderRoutePlanning>(
                                "lat" to mAdapter.data[position].lat,
                                "lon" to mAdapter.data[position].lon,
                                "address" to address,
                                "driverLat" to driverLat,
                                "driverLng" to driverLng,
                                "phone" to mAdapter.data[position].contactMobile,
                                "name" to mAdapter.data[position].contactName
                            )
                        }
                    }
                }
            }
        }

        eventViewModel.toRefreshDataStr.observeInActivity(this) {
            if (it == "ActivityDrippingOrderDetail" || it == "ActivityDovetailSign") {
                onRefresh(true, driverLng, driverLat)
            }
        }
    }

    private fun showCarListDialog(list: ArrayList<CarListBean>) {
        val dialog = RxDialogCarList(this)
        dialog.setList(list)
        dialog.setOnCarPassedListener(object : RxDialogCarList.OnClickCarListener {
            override fun onCarPassed(carId: Int) {
                mCarId = carId
//                CoroutineScope(Dispatchers.IO).launch {//延迟执行操作
//                    delay(500L)
//                    dialog.dismiss()
//                }
            }
        })
        dialog.setCancelListener {
            mCarId = 0
            dialog.dismiss()
        }
        dialog.setSureListener {
            if (mCarId == 0) {
                RxToast.warning("请选择接单车辆")
                return@setSureListener
            }
            receiptOrder(orderId, mCarId)
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun startToDetail(id: Int, orgName: String) {
        startActivity<ActivityDrippingOrderDetail>("id" to id, "orgName" to orgName, "driverLat" to driverLat, "driverLng" to driverLng)
    }

    private fun showSureReceipt(orderId: Int, carId: Int) {
        val dialog = RxDialogDefault(this)
        dialog.setContent("是否确认接单?接单后不可随意退单")
        dialog.setSureListener {
            receiptOrder(orderId, carId)
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun receiptOrder(id: Int, carId: Int) {
        showLoading(getString(R.string.loading))
        val map = mapOf("id" to id, "transporterCarId" to carId, "transporterId" to mTransporterId, "lon" to driverLng, "lat" to driverLat)
        val body: RequestBody = Gson().toJson(map).toRequestBody("application/json".toMediaTypeOrNull())
        mViewModel.receiveOrderDidi(body)
    }

    private fun initLocation() {
        showLoading(getString(R.string.loading))
        //初始化定位客户端
        locationClient = AMapLocationClient(this)
        //配置定位参数
        val locationOption = AMapLocationClientOption()
        locationOption.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
        locationOption.isOnceLocation = true
        //设置定位监听
        locationClient.setLocationListener(locationListener)
        // 启动定位
        locationClient.setLocationOption(locationOption)
        locationClient.startLocation()

        initPermission()
    }

    private val locationListener = AMapLocationListener { location ->
        if (location != null) {
            driverLng = location.longitude
            driverLat = location.latitude
        } else {
            LogUtils.warnInfo("定位失败")
        }
        onRefresh(true, driverLng, driverLat)
    }


    private fun initPermission() {
        XXPermissions.with(this)
            .permission(Permission.ACCESS_FINE_LOCATION)
            .interceptor(PermissionInterceptor())
            .request { _, allGranted ->
                if (allGranted) {
                    // 用户授权成功，重新启动定位
                    locationClient.startLocation()
                } else {
                    // 用户拒绝授权，提示用户手动授权
                    RxToast.warning("定位权限被拒绝，无法获取位置信息")
                }
            }
    }

    private fun onRefresh(b: Boolean, driverLng: Double, driverLat: Double) {
        mViewModel.getOrderDidiListWithTransporter(b, mOrgId, 0, driverLng, driverLat)
    }

    override fun createObserver() {
        super.createObserver()
        /** 查询接鸽员申请中关于汽车的信息列表  */
        mViewModel.carInfoListResult.observe(this) {
            if (it != null && it.list.isNotEmpty()) {
                if (it.list.size == 1) {
                    showSureReceipt(orderId, it.list[0].id)
                } else {
                    showCarListDialog(it.list)
                }
            } else {
                showSingleDialog()
            }
        }
        /** 接订单/指定订单接收（订单状态变更）  */
        mViewModel.receiveOrderResult.observe(this) {
            RxToast.success("接单成功", 3000)
            onRefresh(true, driverLng, driverLat)
        }
        mViewModel.orderListResult.observe(this) {
            loadListData(it, mAdapter, loadsir, mDatabind.includeList.swipeRecyclerView, mDatabind.includeList.swipeRefreshLayout)
        }
    }

    private fun showSingleDialog() {
        val dialog = RxDialogSingle(this)
        dialog.setTitle("暂无车辆，请添加车辆后再进行接单")
        dialog.setSureText("添加车辆")
        dialog.setSureListener {
            startActivity<ActivityAddCarInfo>("orgId" to mOrgId, "type" to "ActivityOrderSquare")
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.includeBar.ivBack, mDatabind.includeBar.tvRightMenu) {
            when (it) {
                mDatabind.includeBar.ivBack -> {
                    finish()
                }

                mDatabind.includeBar.tvRightMenu -> {
                    startActivity<ActivityPigeonCatcherInfo>("orgId" to mOrgId)
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        // 停止定位
        locationClient.stopLocation()
        // 销毁定位客户端
        locationClient.onDestroy()
    }

}